import Vue from 'vue'
import Vuex from 'vuex'
import { request } from 'network/request'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    uid: localStorage.getItem('uid'),
    user: null,
    cart:null
  },
  mutations: {
    updateUserId(state, uid) {
      state.uid = uid;
    },
    user(state, user) {
      state.user = user
    },
    cart(state, cart) {
      state.cart = cart
    }
  },
  actions: {
    // 这边的store相当于$store
    updateUser(store) {
      if (store.state.uid) {
        request({
          url: '/user',
          method: 'get',
          params: {
            id: store.state.uid
          }
        }).then(res => {
          store.commit('user', res[0])
        })
      }
    },
    updateCart(store,callback) {
      if (store.state.uid) {
        request({
          url: '/cart',
          method: 'get',
          params: {
            uid: store.state.uid
          }
        }).then(res => {
          store.commit('cart', res)
          if (callback) {
             callback(store.state.cart)
          }
         
        })
      }
    }
  },
  modules: {
  }
})
